package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.DomainIsDeleteStatusEnum;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/20 - 14:16
 * @Author: Hyoung
 * @Description:
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {


    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private HospitalRepository hospitalRepository;

    /**
     * 保存科室信息到数据库中
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 变成对象
        String jsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);
        // 保存科室前最好能判断一下医院是否存在
        // 判断是否存在
        Hospital hospital = hospitalRepository.findByHoscode(department.getHoscode());
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_NOT_EXIST);
        }

        // 查询医院和部门是否存在
        Department existsDepartment = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (existsDepartment == null) { // 添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        } else { // 修改
            department.setId(existsDepartment.getId());
            department.setUpdateTime(new Date());
            department.setCreateTime(department.getCreateTime());
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(int page, int limit, String hoscode) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 前面传入的是1作为第一页，但是这里的第一页是从0开始的
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);

        Department department = new Department();
        department.setHoscode(hoscode);
        department.setIsDeleted(0); // 考虑逻辑删除的情况
        // 查询
        Example<Department> example = Example.of(department);
        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        //region 不考虑逻辑删除
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        // departmentRepository.deleteById(department.getId());
        //endregion
        department.setIsDeleted(1); // 这个是逻辑删除
        departmentRepository.save(department); // 有id就是修改
    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 查询hoscode医院的所有科室信息
        // TODO 只查询没有删除的Department isDeleted
        List<Department> departmentList = departmentRepository.findByHoscodeAndIsDeleted(hoscode, DomainIsDeleteStatusEnum.UNDELETED.getIsDelete());

        // 根据大科室编号(bigCode)对departmentList进行分组
        Map<String, List<Department>> departmentMap = departmentList.stream()/*.filter(department -> department.getIsDeleted() == 0)*/
                .collect(Collectors.groupingBy(Department::getBigcode));
        // 组装的数据存储
        ArrayList<DepartmentVo> departmentVoArrayList = new ArrayList<>();

        // 遍历map集合
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            String key = entry.getKey();
            List<Department> value = entry.getValue();

            // 组装大科室
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(key); // 设置大科室编号
            departmentVo.setDepname(value.get(0).getBigname()); // 设置大科室名称

            departmentVoArrayList.add(departmentVo);

            // 组装小科室
            ArrayList<DepartmentVo> children = new ArrayList<>();
            for (Department subDepartment : value) {
                DepartmentVo subDepartmentVo = new DepartmentVo();
                subDepartmentVo.setDepcode(subDepartment.getDepcode());
                subDepartmentVo.setDepname(subDepartment.getDepname());
                children.add(subDepartmentVo);
            }
            departmentVo.setChildren(children);
        }
        return departmentVoArrayList;
    }
}
